package netty.io.demo.RPC.proxy;

import netty.io.demo.RPC.client.NettyClient;
import netty.io.demo.RPC.utils.RsUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * 这里是 代理的工具类
 *
 * @author lihh
 */
public class ProxyUtils {
  public static Object getProxyObject(Class clazz) {
    return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new ProxyInvocationHandler(clazz));
  }
  
  /**
   * 代理的 invoke handler
   *
   * @author lihh
   */
  private static class ProxyInvocationHandler implements InvocationHandler {
    private final Class clazz;
    
    public ProxyInvocationHandler(Class clazz) {
      this.clazz = clazz;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      String simpleName = clazz.getSimpleName();
      String name = method.getName();
      
      // 对象转换 bytes
      byte[] requestBytes = RsUtils.createRequestBytes(simpleName, name, args);
      NettyClient.sendMessage(requestBytes);
      return null;
    }
  }
}
